package com.lxm.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lxm.common.contants.ItemConstants;
import com.lxm.common.contants.TradeConstants;
import com.lxm.common.tools.ContentUtils;
import com.lxm.common.tools.ImgUrlUtils;
import com.lxm.common.tools.LogicDeleteUtils;
import com.lxm.common.tools.UserHolder;
import com.lxm.dto.Result;
import com.lxm.dto.TradeDTO;
import com.lxm.entity.Item;
import com.lxm.entity.Login;
import com.lxm.entity.Trade;
import com.lxm.entity.TradeLogic;
import com.lxm.mapper.TradeDao;
import com.lxm.service.ItemService;
import com.lxm.service.LoginService;
import com.lxm.service.TradeService;
import com.lxm.service.logicService.TradeLogicService;
import com.lxm.vo.TradePageVO;
import jakarta.annotation.Resource;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 交易表 服务实现类
 * </p>
 *
 * @author ${author}
 * @since 2024-10-02
 */
@Service
public class TradeServiceImpl extends ServiceImpl<TradeDao, Trade> implements TradeService {

    @Resource
    private ItemService itemService;
    @Resource
    private TradeLogicService tradeLogicService;
    @Resource
    private LoginService loginService;

    @Override
    public Result deleteTrade(Long tradeId) {
        Long userId = UserHolder.getUser().getUserId();
        Trade trade = lambdaQuery().eq(Trade::getTradeId, tradeId)
                .one();
        if (BeanUtil.isEmpty(trade) ) {
            return Result.fail(TradeConstants.TRADE_NOT_EXIST_FAIL);
        }
        if (trade.getTradeStatus() != 3 && trade.getTradeStatus() != 0) {
            return Result.fail(TradeConstants.TRADE_NOT_FINISH_FAIL);
        }
        TradeLogic tradeLogic = BeanUtil.toBean(trade, TradeLogic.class);
        if (!tradeLogic.getBuyer().equals(userId)) Result.fail(TradeConstants.TRADE_NOT_YOURS_FAIL);
        // 逻辑删除
        LogicDeleteUtils.logicDelete(tradeId, tradeLogic,
                tradeLogicService, this);
        return Result.ok(TradeConstants.DELETE_TRADE_SUCCESS);
    }

    @Override
    public Result addTrade(TradeDTO tradeDTO) {
        Long userId = UserHolder.getUser().getUserId();
        Trade trade = BeanUtil.toBean(tradeDTO, Trade.class);
        trade.setBuyer(userId);
        boolean update = itemService.lambdaUpdate()
                .eq(Item::getItemId, tradeDTO.getItemId())
                .ge(Item::getItemNum, tradeDTO.getBuyCount())
                .setSql("item_num=item_num-" + tradeDTO.getBuyCount())
                .update();
        if (!update) {
            return Result.fail(ItemConstants.STACK_NOT_ENOUGH
                    + "," + TradeConstants.TRADE_FAIL);
        }
        Integer money = itemService.lambdaQuery()
                .eq(Item::getItemId, tradeDTO.getItemId())
                .select(Item::getMoney).one()
                .getMoney();
        trade.setTotalMoney(tradeDTO.getBuyCount() * money);
        save(trade);
        return Result.ok(TradeConstants.TRADE_SUCCESS);
    }

    // 历史交易列表
    @Override
    public Result historyTradeList(Integer pageNum) {
        Long userId = UserHolder.getUser().getUserId();
        // 查询已完成交易
        List<Trade> tradeList = lambdaQuery()
                .eq(Trade::getBuyer, userId)
                .eq(Trade::getTradeStatus, 0)
                .orderByDesc(Trade::getCreateTime)
                .select(Trade::getTradeId, Trade::getItemId,
                        Trade::getBuyCount, Trade::getTotalMoney)
                .page(new Page<>(pageNum, TradeConstants.TRADE_PAGE_SIZE))
                .getRecords();
        // 判断是否为空
        if (CollUtil.isEmpty(tradeList)) {
            return Result.ok(tradeList);
        }
        // 转换为VO
        List<TradePageVO> tradePageVOList = tradeList.stream()
                .map(this::getTradePageVO)
                .collect(Collectors.toList());
        return Result.ok(tradePageVOList);
    }

    // 封装VO
    @NotNull
    private TradePageVO getTradePageVO(Trade trade) {
        TradePageVO tradePageVO = BeanUtil.toBean(trade, TradePageVO.class);
        Item item = itemService
                .lambdaQuery()
                .eq(Item::getItemId, trade.getItemId())
                .select(Item::getTitle, Item::getImg, Item::getUserId)
                .one();
        Login userInfoLogin = loginService.getUserInfoLogin(item.getUserId());
        // 设置商品信息
        tradePageVO.setItemTitle(ContentUtils.getBriefEnd(item.getTitle(),
                ItemConstants.ITEM_TITLE_BRIEF));
        // 设置商品封面
        tradePageVO.setItemCoverImg(ImgUrlUtils
                .parseImageCoverUrl(item.getImg()));
        // 设置卖家信息
        tradePageVO.setSellerNickName(userInfoLogin.getNickName());
        tradePageVO.setSellerAvatarUrl(userInfoLogin.getIcon());
        return tradePageVO;
    }
}
